<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-if="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="短链码" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入短链码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="应用ID" prop="appId">
              <el-input v-model="queryParams.appId" placeholder="请输入商户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="expire">
              <el-select v-model="queryParams.expire" placeholder="请选择状态" clearable>
                <el-option label="一次性" value="0"></el-option>
                <el-option label="长效" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <template v-for="dict in pay_link_status" :key="dict.value">
                  <el-option v-if="dict.label != '过期'" :label="dict.label" :value="dict.value" />
                </template>
              </el-select>
            </el-form-item>

            <el-form-item label="过期时间" style="width: 308px">
              <el-date-picker
                v-model="dateRangeUpdateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item label="生成时间" style="width: 308px">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button v-hasPermi="['system:PayLink:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>

            <el-button v-hasPermi="['system:PayLink:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </div>

          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="PayLinkList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="!isClient" v-hasPermi="['pay:payOrder:trader']" label="所属商户" align="center">
          <template #default="{ row }">
            <div class="flex flex-col items-center leading-[1.2] justify-center">
              <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.agentName, '代理名称')">{{
                row.agentName
              }}</el-link>
              <el-icon v-if="row.agentName"><ArrowDown /></el-icon>
              <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.clientName, '商户名称')">{{
                row.clientName
              }}</el-link>
              <el-icon v-if="row.clientName"><ArrowDown /></el-icon>
              <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.appId, '应用ID')">{{
                row.appId
              }}</el-link>
            </div>
          </template>
        </el-table-column>

        <el-table-column v-else label="APP ID" align="center">
          <template #default="{ row }">
            <div class="flex flex-col items-center leading-[1.2] justify-center">
              <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.appId, '应用ID')">{{
                row.appId
              }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="短链" align="center" prop="code">
          <template #default="{ row }">
            <div class="flex flex-col items-center leading-[0.8] justify-center">
              <el-tag class="cursor-pointer" :underline="false" @click="copyText(row.code, '短链码')">{{ row.code }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="国家" align="center" prop="country" />-->
        <el-table-column label="订单总金额" prop="total">
          <template #default="{ row }">
            <span>{{ row.currency }} {{ row.total }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品信息" align="center" prop="product" width="120">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewProduct(row)">查看产品信息</el-button>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="expire">
          <template #default="{ row }">
            <span v-if="row.expire == 0"> <el-tag type="success">一次性</el-tag></span>
            <span v-else><el-tag type="primary">长效</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="pay_link_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.expireTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生成时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['system:PayLink:edit']" link type="primary" icon="CopyDocument" @click="copyLink(scope.row)">复制链接</el-button>
            <el-button v-hasPermi="['system:PayLink:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['system:PayLink:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>
    <!-- 添加或修改支付链接对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="80%" append-to-body>
      <el-form ref="PayLinkFormRef" :model="form" :rules="rules">
        <div class="flex gap-5">
          <div v-if="dialog.type != 'view'" class="w-[550px]">
            <el-form-item label="应用" prop="appId">
              <el-select v-model="form.appId" placeholder="请选择应用" filterable clearable>
                <el-option v-for="item in appList" :key="item.appId" :label="item.appId" :value="item.appId" />
              </el-select>
            </el-form-item>

            <div v-if="form.appId" class="flex justify-between">
              <el-form-item label="商品类型" prop="product">
                <el-select style="width: 160px" :disabled="true" :model-value="goodsType">
                  <el-option v-for="item in product_type" :label="item.label" :value="parseInt(item.value)"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="是否传邮箱" prop="product">
                <el-tag v-if="appList.find((item) => item.appId == form.appId)?.needMail" type="primary">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </el-form-item>

              <el-form-item label="是否传地址" prop="product">
                <el-switch v-model="form.isAddress" active-value="1" inactive-value="0"></el-switch>
              </el-form-item>
            </div>

            <el-form-item label="默认国家" prop="country">
              <el-select v-model="form.country" placeholder="请选择默认国家" filterable clearable>
                <el-option v-for="item in sys_country" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <div class="grid grid-cols-2 gap-4 items-start">
              <el-form-item label="币别" prop="currency">
                <el-select v-model="form.currency" filterable placeholder="请选择货币类型">
                  <el-option v-for="item in currencyList" :label="item.code" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="订单总金额" prop="total">
                <el-input v-model="form.total" placeholder="请输入订单总金额" />
              </el-form-item>
            </div>

            <el-form-item label="支付成功地址" prop="successUrl">
              <el-input v-model="form.successUrl" placeholder="请输入支付成功地址" />
            </el-form-item>
            <el-form-item label="支付失败地址" prop="failureUrl">
              <el-input v-model="form.failureUrl" placeholder="请输入支付失败地址" />
            </el-form-item>
            <el-form-item label="点击返回地址" prop="cancelUrl">
              <el-input v-model="form.cancelUrl" placeholder="请输入点击返回地址" />
            </el-form-item>

            <div v-if="!form.linkId" class="flex items-start gap-5">
              <el-form-item prop="expire" label="订单时效" style="width: 210px; flex-shrink: 0">
                <el-switch
                  v-model="form.expire"
                  class="mb-2"
                  active-text="长效"
                  inactive-text="一次性"
                  :active-value="1"
                  :inactive-value="0"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: var(--el-color-primary)"
                />
              </el-form-item>
              <el-form-item v-if="form.expire == '1'" label="过期时间" prop="time">
                <el-input v-model="form.time">
                  <template #append>小时</template>
                </el-input>
                <div>0表示永久有效</div>
              </el-form-item>
            </div>
            <el-form-item v-else label="过期时间">
              <span v-if="form.expire == 0"> <el-tag type="success">一次性</el-tag></span>
              <span v-else-if="form.expire == 1 && form.expireTime"
                ><el-tag type="primary">{{ form.expireTime }}</el-tag></span
              >
              <span v-else-if="form.expire == 1 && !form.expireTime"> <el-tag type="primary">永久有效</el-tag></span>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in pay_link_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="flex-1">
            <el-table :data="form.product" style="width: 100%; height: 400px" border>
              <el-table-column label="产品名称" prop="post_name" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="产品类型" prop="type" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="产品属性" prop="attributes" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="产品描述" prop="post_content" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="单价" prop="price" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="数量" prop="quantity" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="总价" prop="subtotal" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="产品图片" align="center" width="80">
                <template #default="{ row }">
                  <el-image
                    v-if="row.image"
                    style="width: 50px; height: 50px;object-fit: cover"
                    :src="row.image"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[row.image]"
                    show-progress
                    :initial-index="0"
                    fit="cover"
                  />
                </template>
              </el-table-column>

              <el-table-column v-if="dialog.type != 'view'" width="100" label="操作" align="center">
                <template #default="scope">
                  <el-button type="primary" link size="small" @click="editGoods(scope.row)">编辑</el-button>
                  <el-button type="danger" link size="small" @click="delGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button v-if="dialog.type != 'view'" type="primary" size="large" plain class="mt-2" @click="addGoods">添加产品</el-button>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div v-if="dialog.type != 'view'" class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="goodsDialog.show" width="500px" :title="goodsDialog.title">
      <el-form ref="goodsFormRef" :model="goodsForm" label-width="80" label-position="left" :rules="goodsRules">
        <el-form-item label="产品名称" prop="post_name">
          <el-input v-model="goodsForm.post_name" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model="goodsForm.price" :min="0" style="flex: 1" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="goodsForm.quantity" :min="0" style="flex: 1" />
        </el-form-item>
        <el-form-item v-if="goodsType == 1" label="产品类型" prop="type">
          <el-select v-model="goodsForm.type" placeholder="请选择产品类型">
            <el-option label="variable" value="variable"></el-option>
            <el-option label="simple" value="simple"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="goodsForm.type == 'variable'" label="产品属性" prop="attributes">
          <el-input v-model="goodsForm.attributes" placeholder="请输入产品属性" />
        </el-form-item>
        <el-form-item v-if="goodsType == 1" label="产品描述">
          <el-input v-model="goodsForm.post_content" placeholder="请输入产品描述" />
        </el-form-item>
        <el-form-item label="产品图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="uploadImage.url"
            :headers="uploadImage.header"
            :show-file-list="false"
            accept=".png,.jpg,.jpeg,.webp"
            :on-success="handleProductSuccess"
          >
            <img v-if="goodsForm.image" :src="goodsForm.image" class="avatar w-[100%]" />
            <div class="el-upload--picture-card" v-else>
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="submitGoodsForm">确定</el-button>
        <el-button @click="goodsDialog.show = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayLink" lang="ts">
import { copyTextToClipboard } from '@/directive/common/copyText';
import { listPayApp, getCurrency } from '@/api/pay/PayApp';
import { listPayLink, getPayLink, delPayLink, addPayLink, updatePayLink } from '@/api/pay/PayLink';
import { PayLinkVO, PayLinkQuery, PayLinkForm } from '@/api/pay/PayLink/types';
import useUserStore from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';
const isClient = computed(() => {
  return useUserStore().isClient;
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pay_link_status, sys_country, product_type } = toRefs<any>(proxy?.useDict('pay_link_status', 'sys_country', 'product_type'));

const PayLinkList = ref<PayLinkVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayLinkFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  type: ''
});

const initFormData: PayLinkForm = {
  linkId: undefined,
  appId: undefined,
  country: undefined,
  currency: undefined,
  total: undefined,
  product: [],
  successUrl: undefined,
  failureUrl: undefined,
  cancelUrl: undefined,
  status: 1,
  time: '',
  expire: 0
};

const validatePass2 = (rule, value, callback) => {
  // 去除前后空格
  if (!value) {
    callback(new Error('请输入域名'));
    return;
  }
  let trimmedValue = value.trim();
  const reg = new RegExp(/^(https?:\/\/)/);
  if (!reg.test(trimmedValue)) {
    callback(new Error('请输入正确的跳转地址'));
  } else {
    form.value.domain = trimmedValue;
    callback();
  }
};

const data = reactive<PageData<PayLinkForm, PayLinkQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    code: undefined,
    appId: undefined,
    country: undefined,
    status: undefined,
    createId: undefined,
    agentId: undefined,
    expire: undefined,
    isDelete: undefined,
    params: {}
  },
  rules: {
    appId: [{ required: true, message: 'APP不能为空', trigger: 'blur' }],
    country: [{ required: true, message: '国家不能为空', trigger: 'blur' }],
    currency: [{ required: true, message: '币别不能为空', trigger: 'blur' }],
    total: [{ required: true, message: '订单总金额不能为空', trigger: 'blur' }],
    successUrl: [{ validator: validatePass2, message: '请输入正确的支付成功地址', required: true, trigger: 'blur' }],
    failureUrl: [{ validator: validatePass2, message: '请输入正确的支付失败地址', required: true, trigger: 'blur' }],
    cancelUrl: [{ validator: validatePass2, message: '请输入正确的点击返回地址', required: true, trigger: 'blur' }],
    expire: [{ required: true, message: '订单时效不能为空', trigger: 'blur' }],
    time: [{ required: true, message: '过期时效不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  }
});

const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);
const { queryParams, form, rules } = toRefs(data);

/** 查询支付链接列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  proxy?.addDateRange(queryParams.value, dateRangeUpdateTime.value, 'ExpireTime');
  const res = await listPayLink(queryParams.value);
  PayLinkList.value = res.rows.map((item) => {
    item.product = item.product ? JSON.parse(item.product) : [];
    if (item.expireTime && new Date(item.expireTime).getTime() < new Date().getTime()) item.status = 3;
    return item;
  });
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayLinkFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayLinkVO[]) => {
  ids.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加支付链接';
  dialog.type = 'add';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayLinkVO) => {
  reset();
  const _linkId = row?.linkId || ids.value[0];
  const res = await getPayLink(_linkId);
  res.data.product = JSON.parse(res.data.product);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改支付链接';
  dialog.type = 'edit';
};

/** 提交按钮 */
const submitForm = () => {
  PayLinkFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.product.length <= 0) {
        ElMessage.error('请添加产品');
        return false;
      }
      buttonLoading.value = true;
      form.value.product = JSON.stringify(form.value.product);
      if (form.value.linkId) {
        await updatePayLink(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayLink(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayLinkVO) => {
  const _linkIds = row?.linkId || ids.value.map((item) => item.linkId);
  const _linkNames = row?.code || ids.value.map((item) => item.code);
  await proxy?.$modal.confirm('是否确认删除支付链 ' + _linkNames + ' 数据？').finally(() => (loading.value = false));
  await delPayLink(_linkIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayLink/export',
    {
      ...queryParams.value
    },
    `PayLink_${new Date().getTime()}.xlsx`
  );
};

/*** 查看产品信息 */
const viewProduct = async (row) => {
  const _linkId = row?.linkId || ids.value[0];
  const res = await getPayLink(_linkId);
  res.data.product = JSON.parse(res.data.product);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看产品信息';
  dialog.type = 'view';
};

/**
 * 获取appList
 */
const appList = ref([]);
const getAppList = () => {
  listPayApp({ pageNum: 1, pageSize: 999 }).then((res) => {
    appList.value = res.rows;
  });
};

/**货币类型 */
const currencyList = ref([]);
const getCurrencyList = async () => {
  let res = await getCurrency();
  currencyList.value = res.data;
};

// 商品类型
const goodsType = computed(() => {
  return appList.value.find((item) => item.appId == form.value.appId)?.goodsType;
});

/**
 * 商品操作
 */
const goodsForm = ref({
  post_name: '',
  type: '',
  attributes: '',
  post_content: '',
  price: '',
  quantity: '',
  subtotal: '',
  image: '',
  post_id: ''
});

const goodsDialog = reactive({
  title: '',
  show: false
});

const goodsRules = ref({
  post_name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }],
  attributes: [{ required: true, message: '产品属性不能为空', trigger: 'blur' }]
});

// 添加产品
const addGoods = () => {
  resetGoodsForm();
  goodsDialog.show = true;
  goodsDialog.title = '添加产品';
};
// 编辑产品
const editGoods = (row) => {
  resetGoodsForm();
  goodsDialog.show = true;
  goodsDialog.title = '修改产品';
  goodsForm.value = JSON.parse(JSON.stringify(row));
};
// 删除产品
const delGoods = (index) => {
  ElMessageBox.confirm('此操作将会删除该商品，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      form.value.product.splice(index, 1);
      chengeOrderTotal();
    })
    .catch(() => {});
};

// 清空产品表单
const goodsFormRef = ref(null);
const resetGoodsForm = () => {
  Object.assign(goodsForm.value, {
    post_name: '',
    type: '',
    attributes: '',
    post_content: '',
    price: '',
    quantity: '',
    subtotal: '',
    image: '',
    post_id: ''
  });
  goodsFormRef.value?.resetFields();
};

const submitGoodsForm = () => {
  goodsFormRef.value?.validate(async (valid) => {
    if (valid) {
      goodsForm.value.subtotal = (goodsForm.value.price * 100 * goodsForm.value.quantity) / 100;
      if (goodsForm.value.subtotal <= 0) {
        ElMessage.error('请填写正确的单价或数量');
        return false;
      }
      if (goodsForm.value.post_id) {
        // 修改
        form.value.product[form.value.product.findIndex((item) => item.post_id == goodsForm.value.post_id)] = JSON.parse(
          JSON.stringify(goodsForm.value)
        );
      } else {
        goodsForm.value.post_id = parseInt(Math.random() * 2000) + '' + (new Date().getTime() + '').slice(-4);
        form.value.product.push(JSON.parse(JSON.stringify(goodsForm.value)));
      }
      goodsDialog.show = false;
      chengeOrderTotal();
    }
  });
};

// 复制链接
const copyLink = (row) => {
  copyText(location.origin + '/pay/?code=' + row.code, '支付链接：');
};

//计算订单总金额
const chengeOrderTotal = () => {
  let total = 0;
  form.value.product.map((item) => {
    total += item.subtotal;
  });
  form.value.total = total;
};

// 复制成功
const copyText = (str: string, msg: string) => {
  if (!str) return;
  let newStr = str + '';
  let res = copyTextToClipboard(newStr);
  if (res) {
    ElMessage.success(msg + '复制成功');
  }
};

const uploadImage = reactive({
  header: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/system/upload'
});
const handleProductSuccess = (res) => {
  console.log(res);
  if (res.code == 200) {
    goodsForm.value.image = res.data.url;
  } else {
    ElMessage.error(res.msg);
  }
};

onMounted(() => {
  getList();
  getAppList();
  getCurrencyList();
});
</script>

<style scoped lang="scss"></style>
